package ma.fizazi.missionsmanagement.business.clients.impl;

import java.util.ArrayList;
import java.util.List;

import ma.fizazi.missionsmanagement.business.clients.ClientBusiness;
import ma.fizazi.missionsmanagement.dao.commons.DAOServices;
import ma.fizazi.missionsmanagement.model.Client;
import ma.fizazi.missionsmanagement.model.Contact;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service("clientBusiness")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class ClientBusinessImpl implements ClientBusiness {

	@Autowired
	DAOServices daoServices;

	@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
	public void saveClient(Client client) {
		daoServices.saveEntity(client);
	}

	public Client getClientById(int id) {
		return (Client) daoServices.getEntityById2(Client.class,
				new Integer(id));
	}

	public List<Client> getAllClients() {
		List<Client> clients = null;
		clients = (List<Client>) daoServices.getEntities(Client.class);
		return clients;
	}

//	public List<Client> getActiveClients() {
//		List<Client> allClients = new ArrayList<Client>();
//		List<Client> activeClients = new ArrayList<Client>();
//		allClients = (List<Client>) daoServices.getEntities(Client.class);
//		if (allClients != null) {
//			for (Client client : allClients) {
//				if (client.isActif()) {
//					activeClients.add(client);
//				}
//			}
//		}
//		return activeClients;
//
//	}

	public List<Contact> getContactsOfClient(int clientId) {
		Client client = (Client) daoServices.getEntityById2(Client.class,
				new Integer(clientId));
		System.out.println(client.getContacts());
		return client.getContacts();
	}

//	@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
//	public void disableClient(int clientId) {
//		Client client = (Client) daoServices.getEntityById2(Client.class,
//				clientId);
//		client.setActif(false);
//		daoServices.updateEntity(client);
//	}

	public List<Contact> getActifsContactsOfClient(int clientId) {
		Client client = (Client) daoServices.getEntityById2(Client.class,
				new Integer(clientId));

		List<Contact> allContactsOfClient = client.getContacts();
		List<Contact> actifsContactsOfClient = new ArrayList<Contact>();

		if (allContactsOfClient != null) {
			for (Contact contact : allContactsOfClient) {
				if (contact.isActif()) {
					actifsContactsOfClient.add(contact);
				}
			}
		}
		return actifsContactsOfClient;
	}

}
